package com.xiaoshu.aop;

import com.xiaoshu.annotation.RedisDoubleWrite;
import com.xiaoshu.disruptor.MessageDisruptorQueue;
import com.xiaoshu.disruptor.MethodInfoModel;
import com.xiaoshu.service.BaseDoubleWriteRedisTemplate;
import com.xiaoshu.service.SlaveDoubleWriteRedisTemplate;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description : function description
 * ---------------------------------
 * @Author : deane
 * @Date : Create in 2021/3/20 9:10
 * <p>
 * Copyright (C)2013-2021 小树盛凯科技 All rights reserved.
 */
@Aspect
@Component
public class DoubleWriteAspect {

    MessageDisruptorQueue messageDisruptorQueue;

    @Autowired
    public void setMessageDisruptorQueue(MessageDisruptorQueue messageDisruptorQueue) {
        this.messageDisruptorQueue = messageDisruptorQueue;
    }

    @Pointcut("execution(* com.xiaoshu.service.*.*(..)))")
    private void anyMethod(){
        // define the point;
    }

    /**
     * double write the redis; after master write;
     * @param joinPoint
     */
    @After("anyMethod()")
    public void after(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        Object target = joinPoint.getTarget();
        if(target instanceof BaseDoubleWriteRedisTemplate){
           if(target.getClass().isAnnotationPresent(RedisDoubleWrite.class) || method.isAnnotationPresent(RedisDoubleWrite.class)){
               RedisDoubleWrite annotation = method.getAnnotation(RedisDoubleWrite.class);
               if(!ObjectUtils.isEmpty(annotation)) {
                   if(!annotation.isDoubleWrite()){
                       // if the method is annotation by not Double write; just return;
                       return;
                   }
               }
               // put the slave write event to disruptor queue, then the event will be handle with disruptor handler;
               messageDisruptorQueue.publishEvent(new MethodInfoModel(method, joinPoint.getArgs()));
           }
        }
    }

}
